package thread;
/**
 * 同步块
 * 语法:
 * synchronized(同步监视器对象){
 *     需要多个线程同步执行的代码片段(多线程会产生并发安全问题的代码)
 * }
 *
 * 有效的缩小同步范围是可以在保证并发安全的前提下尽可能提高并发效率
 */
public class SyncDemo2 {
    public static void main(String[] args) {
        Shop shop = new Shop();

        Thread t1 = new Thread("张大大"){
            public void run(){
                shop.buy();
            }
        };
        Thread t2 = new Thread("王大大"){
            public void run(){
                shop.buy();
            }
        };
        t1.start();
        t2.start();

    }
}
    class Shop{
        public synchronized void buy(){
            try{
                Thread t=Thread.currentThread();
                System.out.println(t.getName()+":正在挑衣服");
                Thread.sleep(1000);
                synchronized (this){
                    System.out.println(t.getName()+":正在试衣服");
                    Thread.sleep(1000);
                }

                System.out.println(t.getName()+"：结账离开");
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

